package com.mo.xi.ge.info.help

import android.Manifest
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.telephony.TelephonyManager
import androidx.annotation.RequiresPermission
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import java.net.Inet6Address
import java.net.InetAddress
import java.net.NetworkInterface


/**
 * date:2024/1/27
 **/
object DeviceNetUtil {

    /** 当前IP地址 */
    fun getMobileIp(): String {
        var ip = ""
        try {
            val networkInent = NetworkInterface.getNetworkInterfaces()
            var inet: InetAddress? = null
            while (networkInent.hasMoreElements()) {
                val nextElement = networkInent.nextElement()
                val intADopdses = nextElement.inetAddresses
                while (intADopdses.hasMoreElements()) {
                    inet = intADopdses.nextElement()
                    if (inet is Inet6Address) {
                        continue
                    }
                    val hosdds = inet.hostAddress
                    if (hosdds != "127.0.0.1" && hosdds != null) {
                        ip = hosdds
                        break
                    }
                }
            }
        } catch (e: Exception) {
        }
        return ip
    }

    fun isUsingVpn(context: Context): Boolean {
        var result = false
        try {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networks = connectivityManager.allNetworks
            for (network in networks) {
                val capabilities = connectivityManager.getNetworkCapabilities(network)
                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
                        result = true
                        break
                    }
                }
            }
        } catch (e: Exception) {
        }
        return result
    }

    /** 获取WiFi名称 */
    fun getWifiName(context: Context): String {
        var ssidj: String? = null
        try {
            ssidj = getWifiManager(context).connectionInfo.ssid.orEmpty()
            if (ssidj.contains("unknown ssid")) ssidj = ""
            _getWifiName(context)
        } catch (e: Exception) {
        }
        return ssidj.orEmpty()
    }

    /** 获取WiFimanager */
    private fun getWifiManager(context: Context) =
        context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

    private fun _getWifiName(context: Context): String {
        return context.versionCode().toString()
    }

    /**
     * 获取当前网络连接类型
     * @param context
     * @return
     */
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun getNetworkType(context: Context): String {
        val default = "-"
        //获取系统的网络服务
        val connManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
                ?: return default

        //获取当前网络类型，如果为空，返回无网络
        val activeNetInfo = connManager.activeNetworkInfo
        if (activeNetInfo == null || !activeNetInfo.isAvailable) {
            return default
        }

        // 判断是不是连接的是不是wifi
        val wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        if (null != wifiInfo) {
            val state = wifiInfo.state
            if (null != state) if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                return "WIFI"
            }
        }

        // 如果不是wifi，则判断当前连接的是运营商的哪种网络2g、3g、4g等
        val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
        var result = default
        if (null != networkInfo) {
            val state = networkInfo.state
            val strSubTypeName = networkInfo.subtypeName
            if (null != state) if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                result = getTypeString(networkInfo.subtype, strSubTypeName)
            }
        }
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PermissionChecker.PERMISSION_GRANTED) {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            val typeString = getTypeString(telephonyManager.networkType)
            if (typeString != default) {
                result = typeString
            }
        }
        return result
    }

    private fun getTypeString(subType: Int, subTypeName: String = ""): String {
        return when (subType) {
            TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EDGE,
            TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> "2G"

            TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0,
            TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA,
            TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> "3G"

            TelephonyManager.NETWORK_TYPE_LTE -> "4G"
            TelephonyManager.NETWORK_TYPE_NR -> "5G"
            else ->                             //中国移动 联通 电信 三种3G制式
                if (subTypeName.equals(
                        "TD-SCDMA",
                        ignoreCase = true
                    ) || subTypeName.equals(
                        "WCDMA",
                        ignoreCase = true
                    ) || subTypeName.equals("CDMA2000", ignoreCase = true)
                ) {
                    "3G"
                } else {
                    "?"
                }
        }
    }
}
